/**
 *  total设置小于max，防止出现死循环
 */

// type: ADD, SUBTRACTION, MULTIPLY, DIVIDE

// 生成练习题
const examGenerator = {
  ADD(max) {
    const n1 = randomNum(max)
    const n2 = randomNum(max - n1)
    console.log()
    return [n1, n2]
  },
  SUBTRACTION(max) {
    const n1 = randomNum(max)
    const n2 = randomNum(n1)
    return [n1, n2]
  },
  MULTIPLY(max) {
    const n1 = randomNum(max / 4)
    const n2 = randomNum(max / (n1 || 1))
    return [n1, n2]
  },
  DIVIDE(max) {
    // 获取除以的数字，再根据这个数据获取大的数字，防止超出
    const n2 = randomNum(max > 10 ? 10 : max) || 1
    const n1 = n2 * randomNum(max / (n2 || 1))
    return [n1, n2]
  }
}

// 随机数字
function randomNum(max = 100, min = 0) {
  return Math.floor(Math.random() * (max - min))
}

// 防止重复
function distinct({ examItem = [0, 0], exams = [], type, max, index = 0 }) {
  if (index >= 100) {
    return null
  }
  index += 1
  const isHas = exams.some(it => JSON.stringify(it) === JSON.stringify(examItem))
  // console.log('生成exam', index, examItem)
  const generator = examGenerator[type]
  return isHas ? distinct({
    examItem: generator(max), exams, type, max, index
  }) : examItem
}

// 获取练习题目
export function getExam({ type, max = 100, total = 10 }) {
  const exams = []
  for (let i = 0;i < total;i++) {
    const generator = examGenerator[type]
    if (!generator) break
    const examItem = distinct({
      examItem: generator(max), exams, type, max
    })
    if (examItem) {
      exams.push(examItem)
    }
  }
  return exams
}
